#!/usr/bin/env python3
"""
数据库迁移脚本
用于执行数据库迁移操作
"""

import os
import sys
import subprocess
from pathlib import Path


def run_command(command, description):
    """运行命令并显示输出"""
    print(f"\n{'='*60}")
    print(f"执行: {description}")
    print(f"命令: {command}")
    print(f"{'='*60}")
    
    try:
        result = subprocess.run(command, shell=True, check=True, capture_output=True, text=True)
        if result.stdout:
            print("输出:")
            print(result.stdout)
        if result.stderr:
            print("错误输出:")
            print(result.stderr)
        print(f"✅ {description} 成功")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ {description} 失败")
        print(f"错误码: {e.returncode}")
        if e.stdout:
            print("输出:")
            print(e.stdout)
        if e.stderr:
            print("错误输出:")
            print(e.stderr)
        return False


def init_alembic():
    """初始化Alembic"""
    print("初始化Alembic配置...")
    
    # 检查是否已存在alembic目录
    if Path("alembic").exists():
        print("Alembic已初始化，跳过此步骤")
        return True
    
    # 初始化Alembic
    command = "alembic init alembic"
    return run_command(command, "初始化Alembic")


def create_migration(message):
    """创建新的迁移版本"""
    print(f"创建新的迁移版本: {message}")
    command = f'alembic revision --autogenerate -m "{message}"'
    return run_command(command, f"创建迁移版本: {message}")


def upgrade_database():
    """升级数据库到最新版本"""
    print("升级数据库到最新版本...")
    command = "alembic upgrade head"
    return run_command(command, "升级数据库")


def downgrade_database(revision):
    """降级数据库到指定版本"""
    print(f"降级数据库到版本: {revision}")
    command = f"alembic downgrade {revision}"
    return run_command(command, f"降级数据库到 {revision}")


def show_history():
    """显示迁移历史"""
    print("显示迁移历史...")
    command = "alembic history --verbose"
    return run_command(command, "显示迁移历史")


def show_current():
    """显示当前数据库版本"""
    print("显示当前数据库版本...")
    command = "alembic current"
    return run_command(command, "显示当前数据库版本")


def main():
    """主函数"""
    print("3D定制商品生产平台 - 数据库迁移工具")
    print("=" * 60)
    
    if len(sys.argv) < 2:
        print("使用方法:")
        print("  python run_migrations.py init          - 初始化Alembic")
        print("  python run_migrations.py create '描述' - 创建新迁移")
        print("  python run_migrations.py upgrade       - 升级数据库")
        print("  python run_migrations.py downgrade 版本 - 降级数据库")
        print("  python run_migrations.py history       - 显示迁移历史")
        print("  python run_migrations.py current       - 显示当前版本")
        print("  python run_migrations.py full          - 完整流程（创建+升级）")
        return
    
    command = sys.argv[1]
    
    if command == "init":
        init_alembic()
    
    elif command == "create":
        if len(sys.argv) < 3:
            print("错误: 请提供迁移描述")
            return
        message = sys.argv[2]
        create_migration(message)
    
    elif command == "upgrade":
        upgrade_database()
    
    elif command == "downgrade":
        if len(sys.argv) < 3:
            print("错误: 请提供目标版本")
            return
        revision = sys.argv[2]
        downgrade_database(revision)
    
    elif command == "history":
        show_history()
    
    elif command == "current":
        show_current()
    
    elif command == "full":
        # 完整流程：创建迁移并升级
        migration_name = input("请输入迁移描述: ").strip()
        if not migration_name:
            migration_name = "自动生成的迁移"
        
        success = create_migration(migration_name)
        if success:
            upgrade_database()
    
    else:
        print(f"未知命令: {command}")
        print("请使用 'python run_migrations.py' 查看帮助")


if __name__ == "__main__":
    main()